package com.verisette.framework.web.interceptor;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Required;

import org.corp.agi.basic.common.constant.ProjectConstant;
import org.corp.agi.common.bean.Message;
import org.corp.agi.common.config.MessageConfig;
import org.corp.agi.common.constant.CommonConstant;
import org.corp.agi.web.action.BaseAction;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 
 * Ensuring that sensitive information is sent with a POST request 
 * over an encrypted connection and that sensitive account information
 * is kept on the server.
 *
 * @author Pongsatorn Paolanwat(Mix)
 * @since Jan 5, 2011 10:23:16 AM
 * @version 1.0.0
 * @see
 */
public class AllowOnlyPostRequestsInterceptor extends AbstractInterceptor {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(AllowOnlyPostRequestsInterceptor.class);

	MessageConfig messageConfig;
	@Required
	public void setMessageConfig(MessageConfig messageConfig) {
		this.messageConfig = messageConfig;
	}	
	
	/**
	 * Included method name
	 */
	private String[] included;

	public void setIncluded(String included) {
		if (included!=null) {
			this.included = StringUtils.split(included, ", ");
		}
	}
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		if (included!=null) {
			String requestMethod = ServletActionContext.getRequest().getMethod();
			logger.debug("requestMethod:"+requestMethod);
			String callerMethod = invocation.getProxy().getMethod();
			for (String includedMethod : included) {
				if (includedMethod.equals(callerMethod)) {
					logger.debug("Match "+callerMethod);
					if (!"POST".equals(requestMethod)) {
						//Unauthorized : Fail redirect to login page
						Message message = messageConfig.getMessage(ProjectConstant.MESSAGE_CODE_ACC0006);
			        	((BaseAction)invocation.getAction()).saveMessage( CommonConstant.MESSAGE_TYPE_ERROR, message);
			        	
			        	return "forceToErrorPage";
					}
				}
			}
		}
		return invocation.invoke();
	}

//	public static void main(String args[]) {
//		AllowOnlyPostRequestsInterceptor a = new AllowOnlyPostRequestsInterceptor();
//		a.setIncluded("test1,test2, test3 ,test4");
//		String s[] = a.included;
//		for (String string : s) {
//			System.out.println("["+string+"]");
//		}
//	}
}
